<template>
  <div class="orderListRuleForm">
    <panle title='制作团购海报' content="制作团购海报"></panle>
    <el-button class="create_poster" type="primary" size="mini" @click="createdPoster">创建</el-button>
    <!--搜索-->
    <el-form :inline="true" ref="form" :model="form" label-width="100px" class="demo-form-inline">
      <el-form-item label="海报名称:" prop="title">
        <el-input size="mini" placeholder="请输入" v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" size="mini">搜索</el-button>
        <el-button @click="resetForm('form')" size="mini">重置</el-button>
        <el-button size="mini" @click="init()">刷新</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <div class="table-wrap">
      <el-table :data="tableData" v-loading="loading" style="width: 100%;margin-bottom: 20px;" row-key="id" border stripe default-expand-all>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="content" label="海报内容">
          <template slot-scope="scope">
            <el-image :src="scope.row.content" fit="fill" style="width: 60px;height: 60px;"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="海报名称"></el-table-column>
        <el-table-column prop="popu_link_id" label="链接ID"></el-table-column>
        <el-table-column prop="goods_name" label="商品名称"></el-table-column>
        <el-table-column prop="group_date" label="活动时间"></el-table-column>
        <el-table-column prop="people_num" label="几人团"></el-table-column>
        <el-table-column prop="group_hour" label="成团时间（单位：小时）"></el-table-column>
        <el-table-column prop="add_time" label="创建时间"></el-table-column>
        <el-table-column prop="id" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="fa  fa-pencil" @click="uploadPoster(scope.row)">下载</el-button>
            <el-button type="text" size="mini" icon="fa  fa-pencil" @click="editPoster(scope.row,2)">编辑</el-button>
            <el-button type="text" size="mini" icon="fa  fa-pencil" @click="delPoster(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination @size-change="handlePostersSizeChange" @current-change="handlePostersCurrentChange"
                       :current-page="form.pagePostersNumber" :page-sizes="[10, 50, 100, 200]"
                       :page-size="form.pagePostersSize"
                       background layout="total, sizes, prev, pager, next, jumper"
                       :total="form.postersTotal">
        </el-pagination>
      </div>
    </div>
    <!--添加/编辑-->
    <el-dialog :visible.sync="PosterOpen" width="80%" :before-close="handleClose" append-to-body :title="!posterForm.id ? '创建团购海报' : '编辑团购海报'">
      <el-form ref="posterForm" :model="posterForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="添加背景" prop="basemap">
              <div v-if="dialogImageUrl">
                <div calss="qr_father" v-if="popuQrcode">
                  <VueDragResize
                      :z="1"
                      :x="position.x"
                      :y="position.y"
                      @dragstop="onDrag"
                  >
                    <img class="qrCode mover" ref="qRcodeImage" :src="popuQrcode" :width="qr_w" :height="qr_h" />
                  </VueDragResize>
                </div>

                <div class="uploadimgborder">
                  <img ref="dialogImage" v-if="dialogImageUrl" :src="dialogImageUrl" :width="dialogImage_w" />
                  <img v-else src="@/assets/img/uploadimg.jpg" width="30%" height="30%" />
                </div>

              </div>
              <el-button type="primary" @click="openUploadDialBg" size="mini" style="margin-top:10px">上传模板</el-button>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="添加团购链接：" prop="popu_link_id">
              <el-button type="primary" size="mini" @click="selectPopuLink">添加团购链接</el-button>
            </el-form-item>
            <el-table :data="selectPopuItem" style="width: 100%;margin-bottom: 20px;" border stripe default-expand-all v-if="currentPopuShow == true">
              <el-table-column prop="img" label="缩略图">
                <template slot-scope="scope">
                  <el-image :src="scope.row.img" fit="fill" style="width: 60px;height: 60px;"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="商品名称"></el-table-column>
              <el-table-column prop="spec" label="规格(名称/价格（元）/佣金（元）)">
                <template slot-scope="scope">
                  <el-tag v-for="(item,index) in scope.row.spec" :key="index" style="margin-bottom: 10px !important;">
                    {{item.name}}/{{item.price}}/{{item.link_divide_price}}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="group_apply_time" label="活动时间"></el-table-column>
              <el-table-column prop="people_num" label="几人团">
                  <template slot-scope="scope">
                    {{scope.row.people_num}}人团
                  </template>
              </el-table-column>
              <el-table-column prop="group_hour" label="成团时间">
                  <template slot-scope="scope">
                    {{scope.row.group_hour}}小时
                  </template>
              </el-table-column>
              <el-table-column prop="add_time" label="创建时间"></el-table-column>
            </el-table>
          </el-col>

          <el-col :span="24">
            <el-form-item label="海报名称" prop="title">
              <el-input style="width:50%" v-model="posterForm.title" placeholder="请输入名称" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-dialog :visible.sync="popuLinkOpen" width="80%" append-to-body title="选择推广商品链接">
        <div class="table-wrap">
          <el-table :data="tablePopuLinkData" v-loading="loading" style="width: 100%;margin-bottom: 20px;" row-key="id" border stripe default-expand-all>
            <el-table-column prop="img" label="缩略图" width="85">
              <template slot-scope="scope">
                <el-image :src="scope.row.img" fit="fill" style="width: 60px;height: 60px;"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称"></el-table-column>
            <el-table-column prop="link_yard" label="唯一识别码"></el-table-column>
            <el-table-column prop="spec" label="规格(名称/价格（元）/佣金（元）)">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.spec" :key="index" style="margin-bottom: 10px !important;">
                  {{item.name}}/{{item.price}}/{{item.link_divide_price}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="group_date_time" label="活动时间"></el-table-column>
            <el-table-column prop="people_num" label="几人团" width="80">
                <template slot-scope="scope">
                  {{scope.row.people_num}}人团
                </template>
            </el-table-column>
            <el-table-column prop="group_hour" label="成团时间" width="80">
                <template slot-scope="scope">
                  {{scope.row.group_hour}}小时
                </template>
            </el-table-column>
            <!--<el-table-column prop="add_time" label="创建时间"></el-table-column>-->
            <el-table-column prop="link_level" label="级别" width="80">
              <template slot-scope="scope">
                <span v-if="scope.row.link_level == 1">一级</span>
                <span v-else>二级</span>
                <span>链接</span>
              </template>
            </el-table-column>
            <el-table-column prop="user_name" label="创建人"></el-table-column>
            <el-table-column prop="poster_id" label="当前海报" width="145">
              <template slot-scope="scope">
                <el-image v-if="scope.row.poster_id" :src="scope.row.content" fit="fill" style="width: 120px;"></el-image>
                <p v-else>未设置</p>
              </template>
            </el-table-column>
            <el-table-column prop="link_status" label="状态" width="80">
              <template slot-scope="scope">
                <span v-if="scope.row.link_status == 1">上架</span>
                <span v-else>下架</span>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="操作">
              <template slot-scope="scope">
                <div v-if="scope.row.link_status == 1">
                  <el-button v-if="selectPopuItem.length == 0 || selectPopuItem[0].id != scope.row.id" type="text" icon="fa fa-pencil" @click="selectPopu(scope.row)">选择</el-button>
                  <el-button v-if="selectPopuItem.length > 0 && selectPopuItem[0].id == scope.row.id" type="text" icon="fa fa-pencil" @click="cancelSelect(scope.row)">取消选择</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination @size-change="handlePopuSizeChange" @current-change="handlePopuCurrentChange"
                           :current-page="popuForm.pagePopuNumber" :page-sizes="[10, 50, 100, 200]"
                           :page-size="popuForm.pagePopuSize"
                           background layout="total, sizes, prev, pager, next, jumper"
                           :total="popuForm.popuTotal">
            </el-pagination>
          </div>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose" size="small">取 消</el-button>
        <el-button type="primary" @click="!posterForm.id ? submitForm('posterForm') : subEditForm('posterForm')"
                   size="small">确 定</el-button>
      </div>
    </el-dialog>
    <select-posters :show="IsShowPicDig" @update="cleanDiaglog" :selectType="imgnum" @selectSure="selectImgs" :type="0"></select-posters>
  </div>
</template>

<script>
import {
  getGroupList,
  getGroupLinkList,
  createdPoster,
  delPoster,
  getPosterInfo,
  editePoster
} from "@/api/sell/posters/posters";

import Panle from '@/components/Panle';
import PersButton from '@/components/PersButton';
import {hasPermission, isShow} from '@/common/permission';
import {mapState} from "vuex";
import SelectPosters from "@/components/select-posters.vue";
import VueDragResize from 'vue-drag-resize'
import {checkGroupLink} from "@/api/sell/grouplink/grouplink";

export default {
  name:'Examine',
  components: {
    SelectPosters,
    Panle,
    PersButton,
    VueDragResize
  },
  computed:{
    ...mapState({
      userInfo: state => state.member.userInfo,
    }),
  },
  data() {
    return {
      loading:false,
      PosterOpen:false, //添加/编辑弹框是否显示
      IsShowPicDig: false, //选择模板弹框
      popuLinkOpen:false, //选择推广链接弹框
      currentPopuShow:false,
      form: {
        title:'',
        pagePostersSize: 10,
        pagePostersNumber: 1,
        postersTotal: 0,

      },
      posterForm:{
        title:''
      },
      popuForm:{
        pagePopuSize: 10,
        pagePopuNumber: 1,
        popuTotal: 0,
      },
      tableData:[],
      posterData:[],
      tablePopuLinkData:[],
      selectPopuItem:[],
      imgnum: 1, //选择图片数量
      dialogImageUrl: '',
      dialogImageId:'',
      popuQrcode:'',// 二维码
      popuQrcodeBase64:'', //base64位二维码
      position:{
        x:0,
        y:0
      },

      qr_w:'',
      qr_h:'',
      dialogImage_w:720,
      bigImageAspectRatio: 2.55,
    }
  },
  created() {
    this.init(true);
  },
  methods: {
    hasPermission,
    isShow,
    init() {
      this.loading = true;
      getGroupList(this.form).then((res) => {
        this.tableData = res.data.data;
        this.form.postersTotal = res.data.total;
        this.loading = false;
      })
    },

    popuInit(){
      this.loading = true;
      this.popuForm.page = this.popuForm.pagePopuNumber
      this.popuForm.size = this.popuForm.pagePopuSize
      getGroupLinkList(this.popuForm).then((res) => {
        this.tablePopuLinkData = res.data.data;
        this.popuForm.popuTotal = res.data.total;
        this.popuLinkOpen = true;
        this.loading = false;
      })
    },

    //关闭弹框回调
    handleClose(){
      this.PosterOpen = false;
      this.dialogImageUrl = '';
      this.dialogImageId = '';
      this.selectPopuItem = [];
      this.posterForm = {};
      this.popuQrcode = '';
      this.position.x = '';
      this.position.y = '';
    },

    search: function () {
      this.loading = true;
      this.form.pagePostersSize = 10;
      this.form.pagePostersNumber = 1;
      this.init();
    },

    handlePostersSizeChange: function (e) {
      this.form.pagePostersSize = e;
      this.init();
    },

    handlePostersCurrentChange: function (e) {
      this.form.pagePostersNumber = e;
      this.init();
    },

    handlePopuSizeChange: function (e) {
      this.popuForm.pagePopuSize = e;
      this.popuInit();
    },

    handlePopuCurrentChange: function (e) {
      this.popuForm.pagePopuNumber = e;
      this.popuInit();
    },

    resetForm(formName) {
      this.form.title = '';
      this.init();
    },

    createdPoster:function (e){
      this.PosterOpen = true;
      this.currentPopuShow = false;
    },

    selectImgs: function (res) {
      this.IsShowPicDig = true;
      const dataObj = JSON.parse(res[0].pos);
      this.dialogImageUrl = res[0].urls;
      this.dialogImageId = res[0].id;
      this.position.x = dataObj.x;
      this.position.y = dataObj.y;
    },

    cleanDiaglog: function (shows) {
      this.IsShowPicDig = false;
    },

    openUploadDialBg: function () {
      this.IsShowPicDig = true;
    },

    selectPopuLink:function (){
      this.popuInit();
    },

    //选择链接
    selectPopu:function (e){
      this.loading = true;
      const param = {
        'id': e.id,
      };
      checkGroupLink(param).then((res) => {
        if(res.code == 200){
          this.popuQrcodeBase64 = res.data.popu_link_qrcode;
          this.convertBase64ToPng(res.data.popu_link_qrcode,pngData => {
            this.popuQrcode = URL.createObjectURL(pngData);
            this.qr_w = Math.round(this.dialogImage_w / this.bigImageAspectRatio);
            this.qr_h = this.qr_w;
          })
          this.selectPopuItem = [e];
          this.popuLinkOpen = false;
          this.currentPopuShow = true;
          this.loading = false;
        }
      }).catch(error => {
        this.selectPopuItem = [];
        this.currentPopuShow = false;
        this.loading = false;
      });
    },
    //取消选择
    cancelSelect:function (e){
      this.selectPopuItem = [];
      this.currentPopuShow = false;
      this.popuLinkOpen = false;
    },

    //base64 to png
    convertBase64ToPng(base64Data, callback) {
      // 将base64字符串转换为Blob对象
      const byteCharacters = atob(base64Data.split(',')[1]);
      const arrayBuffer = new ArrayBuffer(byteCharacters.length);
      const uintArray = new Uint8Array(arrayBuffer);
      for (let i = 0; i < byteCharacters.length; i++) {
        uintArray[i] = byteCharacters.charCodeAt(i);
      }
      const blob = new Blob([uintArray], { type: 'image/jpeg' });
      callback(blob);
    },

    onDrag(e) {
      this.position.x = e.left;
      this.position.y = e.top;
    },

    // onEnd(event) {
    //   this.position.x = Math.round(event.originalEvent.offsetX - (this.qr_w / 2));
    //   this.position.y = Math.round(event.originalEvent.offsetY - (this.qr_w / 2));
    // },

    //下载海报
    uploadPoster:function(data){
      const link = document.createElement("a");
      link.href = data.content; // 设置为图片的 URL
      link.download = data.title + ".jpg"; // 设置下载文件名
      link.click()
    },

    //删除海报
    delPoster:function(data){
      this.$confirm('确认删除？')
          .then(_ => {
            delPoster(data).then((res)=>{
              if(res.code==200){
                this.msgSuccess(res.msg);
                this.init();
              }else{
                this.msgError(res.msg);
              }
            })
          })
          .catch(_ => {});
    },

    //编辑海报
    editPoster:function(data){
      getPosterInfo(data).then((res)=>{
        if(res.code==200){
          this.PosterOpen = true;
          this.posterForm = res.data.poster;
          this.dialogImageUrl = res.data.poster.basemap;
          this.position.x = res.data.poster.qr_code_position.x;
          this.position.y = res.data.poster.qr_code_position.y;
          this.selectPopuItem = [res.data.popu_link];
          this.dialogImageId = res.data.poster.posters_template_id;
          this.currentPopuShow = true;
          var param = {
            'id':this.selectPopuItem[0].id,
          }
          checkGroupLink(param).then((res) => {
            if(res.code == 200){
              this.popuQrcodeBase64 = res.data.popu_link_qrcode;
              this.convertBase64ToPng(res.data.popu_link_qrcode,pngData => {
                this.popuQrcode = URL.createObjectURL(pngData);
              })
            }
          })
        }else{
          this.msgError(res.msg);
        }
      })
    },

    //创建提交
    submitForm:function(data){
      this.$refs[data].validate((valid) => {
        if (valid) {
          this.posterForm['popu_link_id'] = this.selectPopuItem[0].id;
          this.posterForm['goods_id'] = this.selectPopuItem[0].goods_id;
          this.posterForm['link_yard'] = this.selectPopuItem[0].link_yard;
          this.posterForm['basemap'] = this.dialogImageUrl;
          this.posterForm['popuQrcode'] = this.popuQrcodeBase64;
          this.posterForm['x'] = this.position.x;
          this.posterForm['y'] = this.position.y;
          this.posterForm['posters_template_id'] = this.dialogImageId;
          this.posterForm['type'] = 2;
          this.posterForm['qr_w'] = this.qr_w;
          this.posterForm['qr_h'] = this.qr_h;
          createdPoster(this.posterForm).then((res)=>{
            if(res.code==200){
              this.msgSuccess(res.msg);
              this.PosterOpen=false;
              this.dialogImageUrl = '';
              this.dialogImageId = '';
              this.selectPopuItem = [];
              this.posterForm.title = '';
              this.popuQrcode = '';
              this.position.x = '';
              this.position.y = '';
              this.init();
            }else{
              this.msgError(res.msg);
            }
          })
        }else{
          return false;
        }
      })
    },

    //编辑提交
    subEditForm:function(data){
      this.$refs[data].validate((valid) => {
        if (valid) {
          this.posterForm['link_yard'] = this.selectPopuItem[0].link_yard;
          this.posterForm['posters_template_id'] = this.dialogImageId;
          this.posterForm['x'] = this.position.x;
          this.posterForm['y'] = this.position.y;
          this.posterForm['goods_id'] = this.selectPopuItem[0].goods_id;
          this.posterForm['popuQrcode'] = this.popuQrcodeBase64;
          this.posterForm['basemap'] = this.dialogImageUrl;
          editePoster(this.posterForm).then((res)=>{
            if(res.code==200){
              this.msgSuccess(res.msg);
              this.PosterOpen=false;
              this.dialogImageUrl = '';
              this.dialogImageId = '';
              this.selectPopuItem = [];
              this.posterForm.title = '';
              this.popuQrcode = '';
              this.position.x = '';
              this.position.y = '';
              this.init();
            }else{
              this.msgError(res.msg);
            }
          })
        }else{
          return false;
        }
      })
    },
  }
}

</script>

<style lang="scss" scoped>
.demo-form-inline {
  margin: 20px;

  .el-form-item {
    margin-bottom: 0;
  }
}
.el-form--inline .el-form-item {
  display: inline-block;
  vertical-align: top;
}

.orderListRuleForm .el-form-item {
  margin-bottom: 0;
}

.search-content {
  width: 100%;
  margin: 20px;
}

.create_poster{
  margin-top: 7px;
  float: right;
}

.w50{
  width: 50px !important;
}
.w60{
  width: 60px !important;
}
.w260{
  width: 260px !important;
}
.mr20{
  margin-right: 20px;
}
.qrCode{
  position: absolute;
}
.dragArea{
  position: absolute;
}
.uploadcol{
  width:100%;
  height: 100%;
  position: relative;
}

.qr_father {
  position: relative;
  margin: 0 auto;
}
.vdr.active:before {
  display:none
}
::v-deep .vdr-stick{
  display: none;
}
::v-deep .active{
  display: block;
}
</style>
